package com.ayu.shortlink.settlement.service.bases.strategy;

import com.ayu.shortlink.settlement.common.convention.exception.ClientException;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * 支付创建订单策略的容器
 */
@Component
@RequiredArgsConstructor
public class AbstractPayCreateOrderStrategyContext implements ApplicationContextAware, CommandLineRunner {
    private Map<String,AbstractPayCreateOrderStrategy> context = new HashMap<>();
    private ApplicationContext applicationContext;

    /**
     * 选择然后执行
     * @param mark 策略标识
     * @param requestParam 请求参数
     * @param <REQUEST> 请求泛型
     */
    public <REQUEST> void chooseAndExecute(String mark,REQUEST requestParam){
        AbstractPayCreateOrderStrategy strategy = context.getOrDefault(mark, null);
        if (strategy == null){
            throw new ClientException("没有这个支付策略");
        }
        strategy.execute(requestParam);
    }

    public <REQUEST,RESPONSE> RESPONSE chooseAndExecuteResp(String mark,REQUEST requestParam){
        AbstractPayCreateOrderStrategy strategy = context.getOrDefault(mark, null);
        if (strategy == null){
            throw new ClientException("没有这个支付策略");
        }
        return (RESPONSE) strategy.executeResp(requestParam);
    }
    @Override
    public void run(String... args) throws Exception {
        //根据类型获取支付策略
        Map<String, AbstractPayCreateOrderStrategy> strategyMap = applicationContext.getBeansOfType(AbstractPayCreateOrderStrategy.class);

        strategyMap.forEach((mark,strategy) -> {
            context.put(mark, strategy);
        });
    }

    /**
     * 注入IOC
     * @param applicationContext
     * @throws BeansException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}
